
package com.probiz.estore.customer.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.probiz.estore.common.model.customer.Membership;
import com.probiz.estore.core.service.impl.GenericManagerImpl;
import com.probiz.estore.core.util.I18nUtil;
import com.probiz.estore.customer.dao.MembershipDao;
import com.probiz.estore.customer.service.MembershipManager;
import com.probiz.estore.eai.customerclass.generated.CustomerClass;

/**
 * Membership Business Delegate (Proxy) implementation to handle communication
 * between web and persistence layer. Implementation of MembershipManager
 * interface. Developer introduced interfaces should be declared here. Won't get
 * overwritten.
 */
public class MembershipManagerImpl extends GenericManagerImpl<Membership> implements MembershipManager {

	private MembershipDao	membershipDao	= null;

	public void setMembershipDao(MembershipDao membershipDao) {
		this.membershipDao = membershipDao;
	}
	
	@Override
	protected void initManager() {
		this.dao = membershipDao;
	}

	@Override
	protected void preDelete(Membership entity) {

	}

	@Override
	protected void preSave(Membership entity) {
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#saveFully(com.probiz.estore.common.model.customer.Membership)
	 */
	public Map<String, Object> saveFully(Membership membership){
		Map<String, Object> returnMsgs = new HashMap<String, Object>();
		evict(membership); //必须把membership evict出session 否则会有update操作
		boolean isLevelExist = isLevelExist(membership.getMembershipId(), membership.getMembershipLevel());
		if (isLevelExist) {
			returnMsgs.put("error", I18nUtil.getInstance().getMessage("membership.errors.LevelRepeat"));
			return returnMsgs;
		}
		boolean isUpgradeShopPointValid = isUpgradeShopPointValid(membership);
		if (!isUpgradeShopPointValid) {
			returnMsgs.put("error", I18nUtil.getInstance().getMessage("membership.errors.upgradeShopPointIsInvalid"));
			return returnMsgs;
		}
		save(membership);
		
		return returnMsgs;
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#deleteFully(com.probiz.estore.common.model.customer.Membership)
	 */
	public Map<String, Object> deleteFully(Membership membership){
		Map<String, Object> returnMsgs = new HashMap<String, Object>();
		if (membership.isBaseMembership()) {
			//默认会员等级不允许删除
			returnMsgs.put("error", I18nUtil.getInstance().getMessage("membership.cannotDeletedDefault",membership.getMembershipName()));
			evict(membership); //必须把membership evict出session 否则会有update操作
			return returnMsgs;
		}
		Membership lowerMembership = getLowerLevelMembership(membership.getMembershipLevel());
		//将所有关联到该等级的会员自动设置为前一等级
		membershipDao.doUpdateCustomerMembership(membership.getMembershipId(),lowerMembership.getMembershipId());
		delete(membership);
		return returnMsgs;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#getLowerLevelMembership(java.lang.Integer)
	 */
	public Membership getLowerLevelMembership(Integer level){
		return membershipDao.getLowerLevelMembership(level);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#getHigherLevelMembership(java.lang.Integer)
	 */
	public Membership getHigherLevelMembership(Integer level){
		return membershipDao.getHigherLevelMembership(level);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#getBaseMembership()
	 */
	public Membership getBaseMembership() {
		return getMembershipByLevel(Membership.MEMBERSHIP_LEVEL_BASE);
	}
	

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#getMembershipByName(java.lang.String)
	 */
	public List<Membership> getMembershipByName(String name) {
		return this.listByProperty("membershipName", name);
	}

	public Membership getMembershipByLevel(Integer level) {
		List<Membership> list= this.listByProperty("membershipLevel", level);
		if(list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#isLevelExist(java.lang.Integer, java.lang.Integer)
	 */
	public boolean isLevelExist(Integer membershipId, Integer level) {
		return membershipDao.isLevelExist(membershipId, level);
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#getAllMembershipsOrderByLevel(boolean)
	 */
	public List<Membership> getAllMembershipsOrderByLevel(boolean isAsc){
		return membershipDao.getAllMembershipsOrderByLevel(isAsc);
	}
	/**
	 * 获取除membershipId以外的等级列表
	 * @param isAsc
	 * @param membershipId
	 * @return
	 */
	private List<Membership> getAllMembershipsOrderByLevelExcluedOne(boolean isAsc,Integer membershipId){
		return membershipDao.getAllMembershipsOrderByLevelExcluedOne(isAsc,membershipId);
	}


	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#isUpgradeShopPointValid(com.probiz.estore.common.model.customer.Membership)
	 */
	public boolean isUpgradeShopPointValid(Membership membership) {
		//必须用这方法，否则间接update了想修改的实体。
		List<Membership> memberships = membershipDao.getAllMembershipsOrderByLevelExcluedOne(true,membership.getMembershipId());
		for(Membership entity:memberships){
			
			if(entity.compareTo(membership) < 0){
				//存在较低等级，必须确保升级积分较多
				if(entity.getUpgradeShopPoint() < membership.getUpgradeShopPoint()){
					continue;
				}else{
					return false;
				}
				
			}
			if(entity.compareTo(membership) > 0){
				//存在较高等级，必须确保升级积分较低
				if(entity.getUpgradeShopPoint() > membership.getUpgradeShopPoint()){
					continue;
				}else{
					return false;
				}
				
			}
		}
		return true;
//		// 如果只有0条记录满足,就不用比较了,直接返回true;
//		if (memberships.size() == 0) {
//			return true;
//		}
//
//		if (membership.getUpgradeShopPoint() != null && membership.getUpgradeShopPoint() == -1) {
//			return true;
//		}
//
//		for (int i = 0; i < memberships.size(); i++) {
//			Membership _membership = memberships.get(i);
//			if (_membership.getUpgradeShopPoint() == null) {
//				return true;
//			}
//			if (membership.getMembershipLevel() > _membership.getMembershipLevel()) {
//				if (i == 0) {
//					if (membership.getUpgradeShopPoint() > _membership.getUpgradeShopPoint())
//						return true;
//				} else {
//					Membership premembership = memberships.get(i - 1);
//					if (membership.getUpgradeShopPoint() > _membership.getUpgradeShopPoint()
//							&& membership.getUpgradeShopPoint() < premembership.getUpgradeShopPoint())
//						return true;
//				}
//				break;
//			}
//		}
//
//		/**
//		 * 如果在修改状态下所有满足的记录的会员等级和升级积分都比修改的记录大的状态,此时要保证这种状态,只需比较最后一条
//		 * *如:修改状态下只有1-n条记录9->900,8->800,7->700 当前修改记录4->400
//		 */
//		if (membership.getMembershipId() != null) {
//			Membership _membership = memberships.get(memberships.size() - 1);
//			if (_membership.getUpgradeShopPoint() == null) {
//				return true;
//			}
//			if (membership.getMembershipLevel() < _membership.getMembershipLevel()
//					&& membership.getUpgradeShopPoint() < _membership.getUpgradeShopPoint()) {
//				return true;
//			}
//
//		}
//
//		return false;

	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#doImportMebershipsForEai(java.util.List)
	 */
	public void doImportMebershipsForEai(List<CustomerClass> customerClassList) {
		// 导入叶子的membership
		for (CustomerClass customerClass : customerClassList) {
			String endRankFlag = customerClass.getEndRankFlag();
			if ("1".equals(endRankFlag)) {
				doImportMembershipForEai(customerClass);
			}
		}

	}
	/**
	 * 导入单条 eai
	 * @param customerClass
	 */
	private void doImportMembershipForEai(CustomerClass customerClass) {
		String code = customerClass.getCode();
		Membership membership = this.getMembershipByCode(code);
		Map map = this.membershipDao.getMaxMemberLevelAndUpgradeShopPoint();
		String mlevel = map.get("membershipLevel").toString();
		String shopPoint = map.get("upgradeShopPoint").toString();

		int maxMemberLevel = (new Integer(mlevel)).intValue() + 1;
		int upgradeShopPoint = (new Integer(shopPoint)).intValue() + 1;
		if (membership == null) {// new
			membership = new Membership();
			membership.setMembershipName(customerClass.getName());
			membership.setMembershipDetail(customerClass.getName());
			membership.setMembershipCode(code);
			membership.setUpgradeShopPoint(upgradeShopPoint);
			membership.setRank(new Integer(customerClass.getRank()));
			membership.setMembershipLevel(maxMemberLevel);//
		} else {
			membership.setMembershipName(customerClass.getName());
			membership.setMembershipCode(code);
			membership.setRank(new Integer(customerClass.getRank()));

		}
		this.membershipDao.save(membership);

	}

	

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.customer.service.MembershipManager#getMembershipByCode(java.lang.String)
	 */
	public Membership getMembershipByCode(String membershipCode) {
		List<Membership>  list =  this.listByProperty("membershipCode",membershipCode);
		if(list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}

	
}